#!/usr/bin/env python

# Copyright European Organization for Nuclear Research (CERN)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# You may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Authors:
# - Vincent Garonne, <vincent.garonne@cern.ch>, 2012
# - Martin Barisits, <martin.barisits@cern.ch>, 2015-2018

from __future__ import with_statement
import os
import re
import subprocess
import sys
import tempfile
import docker


def system(*args, **kwargs):
    kwargs.setdefault('stdout', subprocess.PIPE)
    proc = subprocess.Popen(args, **kwargs)
    out, err = proc.communicate()
    return out

def container(*args, **kwargs):
    client = docker.from_env()
    return client.containers.run(*args, **kwargs)


def main():
    currentbranch = system('git', 'rev-parse', '--abbrev-ref=strict', 'HEAD').rstrip('\n')
    if currentbranch == 'master' or currentbranch == 'next' or currentbranch == 'hotfix':
        print "You are trying to commit on your master/next/hotfix, that's probably a mistake. Exiting..."
        sys.exit(1)
    modified = re.compile('^[AM]+\s+(?P<name>.*\.py)', re.MULTILINE)
    files = system('git', 'status', '--porcelain')
    files = modified.findall(files)
    tempdir = tempfile.mkdtemp()
    for name in files:
        filename = os.path.join(tempdir, name)
        filepath = os.path.dirname(filename)
        if not os.path.exists(filepath):
            os.makedirs(filepath)
        with file(filename, 'w') as f:
            system('git', 'show', ':' + name, stdout=f)

    # Run flake8 on stages files
    f = open(tempdir + '/.flake8', 'w+')
    f.write('''[pycodestyle]
max-line-length=256
ignore=E722

[flake8]
max-line-length=256
ignore=E722
''')
    f.close()
    output = system('flake8', '.', cwd=tempdir)
    if output:
        print output,
        sys.exit(1)

    # Run pylint on stages files inside a rucio-dev container
    tools_path = '{cwd}/tools'.format(cwd = os.getcwd())
    bin_path = '{cwd}/bin'.format(cwd = os.getcwd())
    lib_path = '{cwd}/lib'.format(cwd = os.getcwd())
    for path, subdirs, files in os.walk(tempdir):
        for filename in files:
            if filename.endswith('.py'):
                filepath = '{p}/{f}'.format(p=path, f=filename)
                output = container('rucio/rucio-dev', command=['pylint', '-E', '{f}'.format(f=filename)],
                                   remove = True,
                                   volumes = {tools_path: {'bind': '/opt/rucio/tools', 'mode': 'ro'},
                                              bin_path: {'bind': '/opt/rucio/bin', 'mode': 'ro'},
                                              lib_path: {'bind': '/opt/rucio/lib', 'mode': 'ro'},
                                              lib_path: {'bind': '/opt/rucio/lib', 'mode': 'ro'},
                                              filepath: {'bind': '/opt/rucio/{f}'.format(f=filename), 'mode': 'ro'}})
                if output:
                    print output,
                    sys.exit(1)


if __name__ == '__main__':
    main()
